package com.fin.zw.intelligentbot.listen;

import com.alibaba.fastjson.JSONObject;
import com.fin.zw.intelligentbot.enums.TaskStatus;
import com.fin.zw.intelligentbot.model.ListenResponse;
import com.fin.zw.intelligentbot.service.DialTaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "task_response")
public class CommonListener {

    private static final Logger log = LoggerFactory.getLogger(CommonListener.class);

    @Autowired
    private DialTaskService dialTaskService;

    /**
     * 监听消费消息
     *
     * @param message
     */
    @RabbitHandler
    public void consumeMessage(@Payload byte[] message) {
        try {
            //TODO：接收String
            String result = new String(message, "GBK");
            log.info("接收String消息： {} ", result);
            JSONObject json = JSONObject.parseObject(result);
            ListenResponse listenResponse = JSONObject.toJavaObject(json, ListenResponse.class);
            if (listenResponse.getCode() == 0) {
                if (listenResponse.getCmd().equals("cancel")) {
                    dialTaskService.saveTaskStatus(listenResponse.getTaskId(), TaskStatus.CANCEL);
                } else if (listenResponse.getCmd().equals("start")) {
                    log.info("推送任务成功，任务id:" + listenResponse.getTaskId());
                    dialTaskService.saveTaskStatus(listenResponse.getTaskId(), TaskStatus.READY);
                }
            } else {
                log.info("任务消息发送失败，id为：" + listenResponse.getTaskId());
            }
        } catch (Exception e) {
            log.error("监听消费消息 发生异常： ", e.fillInStackTrace());
        }
    }
}
